import { query } from '../config/db.js';
import logger from '../config/logger.js';
import cache from '../config/redis.js';

/**
 * 获取所有社团
 */
const getClubs = async (req, res) => {
  try {
    // 尝试从缓存获取
    const cacheKey = 'clubs:all';
    const cachedClubs = await cache.get(cacheKey);

    if (cachedClubs) {
      logger.info('从缓存获取社团列表');
      // 检查cachedClubs是否已经是对象
      if (typeof cachedClubs === 'object') {
        return res.json({
          clubs: cachedClubs
        });
      } else {
        // 尝试解析为JSON
        try {
          return res.json({
            clubs: JSON.parse(cachedClubs)
          });
        } catch (jsonError) {
          logger.error(`解析缓存的JSON失败: ${jsonError.message}`);
          // 如果解析失败，返回空数组或错误信息
          return res.json({
            clubs: []
          });
        }
      }
    }

    // 缓存未命中，从数据库获取
    const result = await query('SELECT * FROM clubs');
    const clubs = result.rows;

    // 存入缓存，设置10分钟过期
    await cache.set(cacheKey, clubs, 600); // 直接传递对象，让cache.set处理序列化
    logger.info('从数据库获取社团列表并缓存');

    res.json({
      clubs
    });
  } catch (error) {
    logger.error('获取社团列表错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 根据ID获取社团
 */
const getClubById = async (req, res) => {
  try {
    const { id } = req.params;
    const cacheKey = `clubs:${id}`;

    // 尝试从缓存获取
    const cachedClub = await cache.get(cacheKey);

    if (cachedClub) {
      logger.info(`从缓存获取社团ID: ${id}`);
      // 检查cachedClub是否已经是对象
      if (typeof cachedClub === 'object') {
        return res.json({
          club: cachedClub
        });
      } else {
        // 尝试解析为JSON
        try {
          return res.json({
            club: JSON.parse(cachedClub)
          });
        } catch (jsonError) {
          logger.error(`解析缓存的JSON失败: ${jsonError.message}`);
          // 如果解析失败，从数据库获取
          const result = await query('SELECT * FROM clubs WHERE id = ?', [id]);

          if (result.rows.length === 0) {
            return res.status(404).json({
              message: '社团不存在'
            });
          }

          const club = result.rows[0];
          // 更新缓存
          await cache.set(cacheKey, club, 600);
          logger.info(`缓存解析失败，从数据库获取社团ID: ${id}并更新缓存`);

          return res.json({
            club
          });
        }
      }
    }

    // 缓存未命中，从数据库获取
    const result = await query('SELECT * FROM clubs WHERE id = ?', [id]);

    if (result.rows.length === 0) {
      return res.status(404).json({
        message: '社团不存在'
      });
    }

    const club = result.rows[0];

    // 存入缓存，设置10分钟过期
    await cache.set(cacheKey, club, 600); // 直接传递对象，让cache.set处理序列化
    logger.info(`从数据库获取社团ID: ${id}并缓存`);

    res.json({
      club
    });
  } catch (error) {
    logger.error(`根据ID获取社团错误: ${error.message}`);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 根据名称获取社团
 */
const getClubByName = async (req, res) => {
  console.log('根据名称查询社团请求参数:', req.query);
  try {
    const { name } = req.query;
    if (!name) {
      return res.status(400).json({
        message: '社团名称不能为空'
      });
    }

    const cacheKey = `clubs:name:${name}`;

    // 尝试从缓存获取
    const cachedClub = await cache.get(cacheKey);
    console.log('根据名称查询社团缓存结果:', cachedClub);
    if (cachedClub) {
      logger.info(`从缓存获取社团名称: ${name}`);
      // 检查cachedClub是否已经是对象
      if (typeof cachedClub === 'object') {
        return res.json({
          club: cachedClub
        });
      } else {
        // 尝试解析为JSON
        try {
          return res.json({
            club: JSON.parse(cachedClub)
          });
        } catch (jsonError) {
          logger.error(`解析缓存的JSON失败: ${jsonError.message}`);
          // 如果解析失败，直接返回缓存的原始值
          return res.json({
            club: cachedClub
          });
        }
      }
    }

    // 缓存未命中，从数据库获取
    const result = await query('SELECT * FROM clubs WHERE club_name = ?', [name]);
    console.log('根据名称查询社团结果:', result);
    if (result.rows.length === 0) {
      return res.status(404).json({
        message: '社团不存在'
      });
    }

    const club = result.rows[0];

    // 存入缓存，设置10分钟过期
    await cache.set(cacheKey, club, 600); // 直接传递对象，让cache.set处理序列化
    logger.info(`从数据库获取社团名称: ${name}并缓存`);

    res.json({
      club
    });
  } catch (error) {
    logger.error(`根据名称获取社团错误: ${error.message}`, error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};


/**
 * 创建新社团
 */
const createClub = async (req, res) => {
  try {
    const { club_name, member_count, location, remarks } = req.body;

    // 检查社团是否已存在
    const existingClub = await query('SELECT * FROM clubs WHERE club_name = ?', [club_name]);

    if (existingClub.rows.length > 0) {
      return res.status(400).json({
        message: '社团名称已存在'
      });
    }

    // 创建新社团
    await query(
      'INSERT INTO clubs (club_name, member_count, location, remarks) VALUES (?, ?, ?, ?)',
      [club_name, member_count, location, remarks]
    );

    // 获取创建的社团
    const selectResult = await query(
      'SELECT * FROM clubs WHERE club_name = ?',
      [club_name]
    );

    const newClub = selectResult.rows[0];
    logger.info(`社团创建: ${newClub.club_name} (ID: ${newClub.id})`);

    // 清除相关缓存
    await cache.del('clubs:all');

    res.status(201).json({
      message: '社团创建成功',
      club: newClub
    });
  } catch (error) {
    logger.error(`创建社团错误: ${error.message}`);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 更新社团
 */
const updateClub = async (req, res) => {
  try {
    const { id } = req.params;
    const { club_name, member_count, location, remarks } = req.body;

    // 检查社团是否存在
    const existingClub = await query('SELECT * FROM clubs WHERE id = ?', [id]);

    if (existingClub.rows.length === 0) {
      return res.status(404).json({
        message: '社团不存在'
      });
    }

    // 检查社团名称是否已被其他社团使用
    const clubWithSameName = await query(
      'SELECT * FROM clubs WHERE club_name = ? AND id != ?',
      [club_name, id]
    );

    if (clubWithSameName.rows.length > 0) {
      return res.status(400).json({
        message: '社团名称已存在'
      });
    }

    // 更新社团
    await query(
      'UPDATE clubs SET club_name = ?, member_count = ?, location = ?, remarks = ? WHERE id = ?',
      [club_name, member_count, location, remarks, id]
    );

    // 获取更新后的社团
    const updatedClub = await query('SELECT * FROM clubs WHERE id = ?', [id]);

    logger.info(`社团更新: ${updatedClub.rows[0].club_name} (ID: ${id})`);

    // 清除相关缓存
    await cache.del('clubs:all');
    await cache.del(`clubs:${id}`);

    res.json({
      message: '社团更新成功',
      club: updatedClub.rows[0]
    });
  } catch (error) {
    logger.error(`更新社团错误: ${error.message}`);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 删除社团
 */
const deleteClub = async (req, res) => {
  try {
    const { id } = req.params;

    // 检查社团是否存在
    const existingClub = await query('SELECT * FROM clubs WHERE id = ?', [id]);

    if (existingClub.rows.length === 0) {
      return res.status(404).json({
        message: '社团不存在'
      });
    }

    // 删除社团
    await query('DELETE FROM clubs WHERE id = ?', [id]);

    logger.info(`社团删除: ${existingClub.rows[0].club_name} (ID: ${id})`);

    // 清除相关缓存
    await cache.del('clubs:all');
    await cache.del(`clubs:${id}`);

    res.json({
      message: '社团删除成功'
    });
  } catch (error) {
    logger.error(`删除社团错误: ${error.message}`);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

export {
  getClubs,
  getClubById,
  getClubByName,
  createClub,
  updateClub,
  deleteClub
};